package com.zw.yzk.kabu.presenter;

import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.Configuration;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.base.BaseSubscriber;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.network.task.Task;
import com.zw.yzk.kabu.data.network.task.PublishCosTask;
import com.zw.yzk.kabu.domain.repository.UseCase;
import com.zw.yzk.kabu.management.LoadingDialogManager;
import com.zw.yzk.kabu.management.ToastManager;
import com.zw.yzk.kabu.mapper.PublishMapper;
import com.zw.yzk.kabu.model.PublishImageModel;
import com.zw.yzk.kabu.utils.StringUtils;
import com.zw.yzk.kabu.view.view.PublishCosView;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import javax.inject.Inject;
import javax.inject.Named;

/**
 * Created by zhanwei on 2017/1/16.
 */

public class PublishCosPresenter implements Presenter {

    private UseCase publishCos;
    private UseCase getUploadToken;
    private AppCompatActivity activity;
    private PublishCosView publishCosView;
    private PublishMapper mapper;
    private UploadManager uploadManager;
    private PublishCosTask publishTask;
    private List<String> qiniuUrl;
    private boolean cancel;
    private int uploadedItem;

    @Inject
    public PublishCosPresenter(@Named("publishUseCase") UseCase publishCos,
                               @Named("uploadImageTokenUseCase") UseCase getUploadToken,
                               AppCompatActivity appCompatActivity,
                               PublishMapper mapper) {
        this.publishCos = publishCos;
        this.getUploadToken = getUploadToken;
        this.activity = appCompatActivity;
        this.mapper = mapper;
    }

    public void setView(PublishCosView view) {
        this.publishCosView = view;
    }

    public void publish(String address, final List<PublishImageModel> modelList, String topContent, final String token) {
        List<String> topicList = new ArrayList<>();
        List<String> tmpList = StringUtils.divideString(topContent, StringUtils.DIVIDE_STRING_PATTERN1);
        for (String str : tmpList) {
            topicList.add(str.replace("#", ""));
        }
        List<String> names = new ArrayList<>();
        List<String> nickName = StringUtils.divideString(topContent, StringUtils.DIVIDE_STRING_PATTERN2);
        for(String str: nickName) {
            names.add(str.replace("@", ""));
        }
        publishTask = new PublishCosTask(mapper.transfer(modelList), topicList, names, address, topContent, token);
        cancel = false;
        new Thread(new Runnable() {
            @Override
            public void run() {
                uploadToQiNiu(modelList, token);
            }
        }).start();
    }

    private void uploadToQiNiu(List<PublishImageModel> data, String token) {
        if (uploadManager == null) {
            uploadManager = new UploadManager(
                    new Configuration.Builder()
                            .build());
        }
        if (qiniuUrl == null) {
            qiniuUrl = new ArrayList<>();
        }
        qiniuUrl.clear();
        uploadedItem = 0;
        while (true) {
            if (cancel) {
                break;
            }
            if (uploadedItem == qiniuUrl.size()) {
                String expectKey = UUID.randomUUID().toString();
                if (qiniuUrl.size() == data.size()) {
                    //图片已经全部上传完成，将结果组装完成上传到服务器
                    publishCos.execute(new PublishCosSubscriber(activity), publishTask);
                    return;
                }
                uploadManager.put(data.get(uploadedItem).getContentPath(), expectKey, token, new UpCompletionHandler() {
                    public void complete(String k, ResponseInfo info, JSONObject response) {
                        if (info.isOK()) {
                            getImageUrl(response);
                        } else {
                            cancel = true;
                            LoadingDialogManager.getInstance().dismissLoadingDialog();
                            ToastManager.getInstance().showToast(activity, activity.getResources().getString(R.string.upload_image_failed));
                        }
                    }
                }, null);
                uploadedItem++;
            }
        }
    }

    private synchronized void getImageUrl(JSONObject response) {
        String url = response.optString("key");
        qiniuUrl.add(url);
        publishTask.cosList.get(qiniuUrl.size() - 1).imageUrl = ActivityConstant.QINIU_PERFIX + url;
    }

    public void getUploadImageToken() {
        getUploadToken.execute(new GetUploadTokenSubscriber(activity), new Task());
    }

    @Override
    public void resume() {

    }

    @Override
    public void pause() {

    }

    @Override
    public void destroy() {
        publishCos.isUnsubscribed();
        getUploadToken.unSubscribe();
    }

    private class PublishCosSubscriber extends BaseSubscriber<Boolean> {

        public PublishCosSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onCompleted() {
            super.onCompleted();
            LoadingDialogManager.getInstance().dismissLoadingDialog();
        }

        @Override
        public void onNext(Boolean aBoolean) {
            super.onNext(aBoolean);
            ToastManager.getInstance().showToast(activity, activity.getResources().getString(R.string.publish_success));
            if (aBoolean) {
                publishCosView.publishSuccess();
            }
        }

        @Override
        public String addErrorMessage() {
            return activity.getResources().getString(R.string.publish_cos_fail);
        }

    }

    private class GetUploadTokenSubscriber extends BaseSubscriber<String> {

        public GetUploadTokenSubscriber(AppCompatActivity appCompatActivity) {
            super(appCompatActivity);
        }

        @Override
        public void onNext(String s) {
            super.onNext(s);
            publishCosView.getUploadImageTokenSuccess(s);
        }

        @Override
        public String addErrorMessage() {
            return activity.getResources().getString(R.string.get_upload_image_token_failed);
        }
    }
}
